#Author : Meng Zhang

import re
import string
import datetime

eventParser = re.compile('([\S]*)[ ]*{([^}]*)}')
propertyParser = re.compile('[ ]*([+-]?)[ ]*([\S]*)[ ]*([\S]*;)([ ]*[^\n]*)')

def UpperFirst(s):
    return s[0].upper() + s[1:]

def parse(filename):
    Events = {}
    input = file (filename,'r')
    content = input.read();
    content =  eventParser.finditer(content)
    for event in content:
        p = event.group(2)
        p = p.split('\n') #got all properties

        key = event.group(1)
        key += 'Event'
        key = UpperFirst(key)
            
        while '' in p:
            p.remove('')
        Events[key] = []
    
        for k in p:
                v = list(propertyParser.match(k).groups())
                Events[key].append(v);
        
    return Events

def GenMethod(eventName):
    event = eventName.replace('Event','')
    return '    static EventType type() {' + ' return ' + event + '; }\n' + '    virtual EventType GetType() const {' + ' return ' + event + '; }\n'

def GenStruct(Events):
    ret = ''
    for event in Events:
        ret += 'struct ' + event + ' : public Event {\n'
        ret += GenMethod(event);
        for property in Events[event]:
            if (property[0]=='+'):
                property[0] = '__in'
            elif (property[0]== '-'):
                property[0] = '__out'
        for property in Events[event]:
            ret+= '    '
            for key in property:
                ret+= key + ' '
            ret+='\n'
             
        ret+= '};\n\n'
    
    return ret

def Header():
    ret  = '/* This is file is generated by EventGenerator\n'
    ret += ' * Date: ' + str(datetime.datetime.today()) + '\n'
    ret += ' * Author : Meng Zhang\n'
    ret += ' */\n\n'
    ret += '#pragma once\n\n'
    ret += '#include <windows.h>\n#include <vector>\n#include <map>\n#include <set>\n#include <string>\n#include <tchar.h>\n\n'
    ret += 'namespace Events {\n\n'
    ret += GenEnum(Events)
    ret += 'struct Event {\n    virtual EventType GetType() const = 0;\n};\n\n'
    return ret

def Footer():
    return '}\n' 
    
def GenEnum(Events):
    ret = 'enum EventType {\n'
    keys = Events.keys()
    for event in keys:
        enum = event.replace('Event','')
        if (event == keys[0]):
            ret += '    ' + enum + ' = 0, \n'
        else:
            ret += '    ' + enum + ' , \n'
    ret += '};\n\n'
    return ret
    
def WriteFile(Filename,content):
    output = file(Filename,'w')
    output.write(content)
    
if __name__== '__main__':
    Events = parse('EventInterface.txt')
    ret = ''
    ret += Header()
    ret += GenStruct(Events)
    ret += Footer()
    WriteFile('Events.h',ret)
